package cq.zhcqk.axst.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SearchView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.activity.LoginActivity;
import cq.zhcqk.alipay.PayResult;
import cq.zhcqk.app;
import cq.zhcqk.axst.adapter.LeftAdapter;
import cq.zhcqk.axst.entity.Cart;
import cq.zhcqk.axst.entity.Product;
import cq.zhcqk.axst.utils.Parser;
import cq.zhcqk.axst.utils.UIHelper;
import cq.zhcqk.axst.utils.Utils;
import cq.zhcqk.base.BaseActivity;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.ImageLoaderHelper;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.WebViewHeader;
import cq.zhcqk.util.wxapi.Constants;
import cq.zhcqk.util.x5.X5WebView;
import cq.zhcqk.widget.SearchEditText;

/*****************************************************
 * author:      wz
 * email:       wangzhong0116@foxmail.com
 * version:     1.0
 * date:        2017/1/10 11:54
 * description:
 *****************************************************/

public class AxstInfo extends AppCompatActivity
        implements SectionIndexer, View.OnClickListener {

    private Context context;
    private ListView rightListView;          //右侧商品listview
    private ListView leftListView;   //左侧--商品类型listview
    private RightAdapter rightAdapter;   //右侧adapter
    private LeftAdapter leftAdapter;  //左侧adapter
    private ImageView shopCart;//购物车
    private View cartFrame;
    private TextView buyNumView;//购物车上的数量标签
    private TextView mPriceSumView;
    //private View cartView;
    private TextView selectedView;
    private View titleLayout;
    private TextView title;
    private ListView popuListView;
    /**
     * 上次第一个可见元素，用于滚动时记录标识。
     */
    private int lastFirstVisibleItem = -1;
    private List<Product> mProductList;
    private List<Cart> mCartList = new ArrayList<Cart>();

    private ViewGroup anim_mask_layout;//动画层
    private int buyNum = 0;//购买数量


    private int count = 0;
    private double priceSum = 0.0;

    /**
     * 在这里虚构个商家id，其主要目的是不想让大家走更多的弯路
     */
    private int businessId = 0;
    /**
     * 上次选中的左侧菜单
     */
    private View lastView;

    private Dialog dialog;
    private ImageView zfbImg;
    private ImageView wxImg;
    private TextView amount;
    //支付方式1；支付宝，2：微信
    private int payType = 1;

    private AsyncHttpClient httpClient;
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    protected BuildBean buildBean;
    private Activity mActivity;
    private SearchView searchView;

    private String dishname = "";
    private LinearLayout content_layout;
    private ListView listViewSh;
    private RightAdapter adapterSerach;
    private List<Product> mProductListSearch;
    private ImageView header_location;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_list);
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        mActivity = AxstInfo.this;
        context = this;
        api = WXAPIFactory.createWXAPI(context, null);
        initBack();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        UIHelper.clearCart(context, businessId);
//        buyNum = 0;
//        priceSum = 0;
//        showSeleted();

        UIHelper.clearCart(context, businessId);
//        cartFrame.setEnabled(false);
//        popupWindow.dismiss();
        if(rightAdapter != null&& leftAdapter != null){
            rightAdapter.notifyDataSetChanged();
            leftAdapter.notifyDataSetChanged();
        }
        priceSum = 0.0;
        buyNum = 0;
        showSeleted();
    }

    protected void initData() {
        buildBean = DialogUIUtils.showLoading(this, "加载中...", true, false, false, false);
        initViewCur();
        initClick();
        initBack();
        getList(dishname);
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("爱心食堂");
        back.setOnClickListener(this);
    }


    private void initViewCur() {
        titleLayout = findViewById(R.id.title_layout);
        title = (TextView)  findViewById(R.id.title_layout_catalog);
        rightListView = (ListView)  findViewById(R.id.menu_lvmenu);
        shopCart = (ImageView)  findViewById(R.id.iv_add_cart);//购物车
        cartFrame =  findViewById(R.id.cart_frame);
        buyNumView = (TextView)  findViewById(R.id.tv_count_price);//购物车上的数量标签
        mPriceSumView = (TextView)  findViewById(R.id.price_sum_view);
        selectedView = (TextView)  findViewById(R.id.selected_view);
        leftListView = (ListView)  findViewById(R.id.side_menu_lv);
        content_layout = (LinearLayout) findViewById(R.id.df_lay);
        listViewSh = (ListView) findViewById(R.id.menu_lvmenu_1);
        searchView = (SearchView) findViewById(R.id.searchView);
        header_location = (ImageView) findViewById(R.id.header_location);
        int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchView.findViewById(id);
        textView.setTextColor(getResources().getColor(R.color.black_text));
        textView.setHintTextColor(getResources().getColor(R.color.gray));
        // 设置搜索文本监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                getList(query);
                return false;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if(StringUtil.isNull(newText)){
                    dishname = "";
                    getList("");
                }
                return false;
            }

        });
        header_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();

            }
        });
    }

    private void initClick() {
        cartFrame.setOnClickListener(this);
        selectedView.setOnClickListener(this);

        //左侧类型点击对应右侧商品
        leftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (lastView != null) {
                    //上次选中的view变回灰色
                    lastView.setBackgroundColor(getResources().getColor(R.color.frament_tab_color));
                }
                //改变选中状态
                leftAdapter.setCurrentItem(position);
                leftAdapter.notifyDataSetChanged();
                //设置选中颜色为白色
                view.setBackgroundColor(getResources().getColor(R.color.white));
                //点击左侧，右侧滚动到对应的位置
                TextView section_tv = (TextView) view.findViewById(R.id.section_tv);
                int location = rightAdapter.getPositionForSection(
                        (Integer.parseInt(section_tv.getText().toString())));
                if (location != -1) {
                    rightListView.setSelection(location);
                }
                lastView = view;
            }
        });
    }

    private void initSerach(){
        adapterSerach = new RightAdapter(context,mProductListSearch);
        listViewSh.setAdapter(adapterSerach);
        listViewSh.setVisibility(View.VISIBLE);
        content_layout.setVisibility(View.GONE);
    }

    /**
     * 初始化数据
     */
    private void initDataCur() {
        listViewSh.setVisibility(View.GONE);
        content_layout.setVisibility(View.VISIBLE);
        rightAdapter = new RightAdapter(context, mProductList);
        leftAdapter = new LeftAdapter(context, mProductList);
        rightListView.setAdapter(rightAdapter);
        leftListView.setAdapter(leftAdapter);

        rightListView.setOnScrollListener(mOnScrollListener);
        //此处为判断是否为空
//        if (mProductList==null){
//
//        }
    }

    private void getLocation(){
        RequestParams params = new RequestParams();
        String url = "";
        url = Common.URL+Common.LOCATION;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"获取地址信息失败",Toast.LENGTH_SHORT).show();
                    return;
                }
                String address = "address="+ map.get("data")+"";
                String uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                Uri uri = Uri.parse(uristr);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void getList(final String dishname1){
        RequestParams params = new RequestParams();
        params.add("dishname",dishname1);
        String url = "";
        url = Common.URL+Common.DISHESLIST;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"没有搜索到菜品",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(StringUtil.isNull(dishname1)){
                    mProductList = Parser.getCateProductList(context,response+"");
                    initDataCur();
                }else{
                    mProductListSearch = Parser.getCateProductList(context,response+"");
                    initSerach();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    /**
     * 右侧商品滑动对于左侧类型
     */
    private AbsListView.OnScrollListener mOnScrollListener = new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            try {
                //获取屏幕第一个item的section
                int section = getSectionForPosition(firstVisibleItem);
                int nextSection = 0;
                if (mProductList.size() > 1) {
                    nextSection = getSectionForPosition(firstVisibleItem + 1);
                }

                int nextSecPosition = getPositionForSection(+nextSection);
                if (firstVisibleItem != lastFirstVisibleItem) {
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                            .getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(mProductList.get(getPositionForSection(section)).getType());
                    if (lastView != null) {
                        lastView.setBackgroundColor(getResources().getColor(R.color.frament_tab_color));
                    }
                    lastView = leftListView.getChildAt(section);
                    lastView.setBackgroundColor(getResources().getColor(R.color.white));

                }
                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public Object[] getSections() {
        return null;
    }

    @Override
    public int getPositionForSection(int sectionIndex) {
        for (int i = 0; i < mProductList.size(); i++) {
            int section = mProductList.get(i).getSeleteId();
            if (section == sectionIndex) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getSectionForPosition(int i) {
        return mProductList.get(i).getSeleteId();
    }

    /**
     * 创建动画层
     * @return
     */
    private ViewGroup createAnimLayout() {
        ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
        LinearLayout animLayout = new LinearLayout(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setId(Integer.MAX_VALUE - 1);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    private View addViewToAnimLayout(final ViewGroup parent, final View view,
                                     int[] location) {
        int x = location[0];
        int y = location[1];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        view.setLayoutParams(lp);
        return view;
    }

    public void setAnim(final View v, int[] startLocation) {
        anim_mask_layout = null;
        anim_mask_layout = createAnimLayout();
        anim_mask_layout.addView(v);//把动画小球添加到动画层
        final View view = addViewToAnimLayout(anim_mask_layout, v,
                startLocation);
        int[] endLocation = new int[2];// 存储动画结束位置的X、Y坐标
        //TODO 这里需要进行判断购物车是否存在
        shopCart.getLocationInWindow(endLocation);// shopCart是那个购物车

        // 计算位移
        int endX = 0 - startLocation[0] + 20;// 动画位移的X坐标
        int endY = endLocation[1] - startLocation[1];// 动画位移的y坐标
        System.out.println("=====x==="+endX);
        System.out.println("=====y==="+endY);
        TranslateAnimation translateAnimationX = new TranslateAnimation(0,
                endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator()); //让动画已均匀的速度改变
        translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true); //执行完毕，利用视图setLayoutParams来重新定位

        TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
                0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());
        translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(translateAnimationY);
        set.addAnimation(translateAnimationX);
        set.setDuration(800);// 动画的执行时间
        view.startAnimation(set);
        // 动画监听事件
        set.setAnimationListener(new Animation.AnimationListener() {
            // 动画的开始
            @Override
            public void onAnimationStart(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            // 动画的结束
            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.GONE);
                addCart();
            }
        });

    }

    private void addCart() {
        buyNum++;//让购买数量+1
        showSeleted();
    }

    public void removeCart() {
        buyNum--;//让购买数量-1
        showSeleted();
    }

    private void showSeleted() {
        if (buyNum > 0) {
            buyNumView.setVisibility(View.VISIBLE);
            buyNumView.setText(buyNum + "");
            mPriceSumView.setText("共￥:" + convert(priceSum));
            mPriceSumView.setTextColor(getResources().getColor(R.color.big_red));
            if (priceSum > 0) {
                selectedView.setEnabled(true);
                selectedView.setText("选好了");
                selectedView.setBackgroundResource(R.drawable.bg_choice_press_round);
            } else {
                selectedView.setEnabled(false);
                selectedView.setText("选好了");
                selectedView.setBackgroundResource(R.drawable.bg_choice_round);
            }
            shopCart.setImageResource(R.mipmap.cart13);
            cartFrame.setEnabled(true);
            //selectedView.setVisibility(View.VISIBLE);
        } else {
            mPriceSumView.setText("请点餐~");
            mPriceSumView.setTextColor(getResources().getColor(R.color.cart_choice_color));
            selectedView.setEnabled(false);
            selectedView.setText("选好了");
            selectedView.setBackgroundResource(R.drawable.bg_choice_round);
            shopCart.setImageResource(R.mipmap.cart12);
            buyNumView.setVisibility(View.GONE);
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
            cartFrame.setEnabled(false);
            //selectedView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.header_back:
                finish();
                break;
            case R.id.selected_view:
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    context.startActivity(new Intent(context, LoginActivity.class));
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                    return;
                }
                mCartList = UIHelper.getCartList(context, businessId);
                if(mCartList.size()>0){
                    payType = 1;
                    LayoutInflater layoutInflater = LayoutInflater.from(context);
                    View rootView = layoutInflater.inflate(R.layout.custom_dialog_axst, null);
                    zfbImg = (ImageView) rootView.findViewById(R.id.zfbImg);
                    wxImg = (ImageView) rootView.findViewById(R.id.wxImg);
                    amount = (TextView) rootView.findViewById(R.id.amount);
                    amount.setText(priceSum+"");
                    dialog = DialogUIUtils.showCustomAlert(context, rootView, Gravity.CENTER, true, false).show();
                    rootView.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pay(payType);
                        }
                    });
                    rootView.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUIUtils.dismiss(dialog);
                        }
                    });
                    rootView.findViewById(R.id.zhifb).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            payType = 1;
                            setPayImg(payType);
                        }
                    });
                    rootView.findViewById(R.id.wxpay).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            payType = 2;
                            setPayImg(payType);
                        }
                    });
                }else {
                    Toast.makeText(context,"请点餐",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_add_cart:
                initPopWindow();
                break;
            case R.id.cart_frame:
                initPopWindow();
                break;
            case R.id.cart_clear_view:
                //clear cart  === hide cart list

                break;
            default:
                break;
        }
    }

    private void setPayImg(int type){
        if(type == 1){
            wxImg.setImageResource(R.mipmap.check_off);
            zfbImg.setImageResource(R.mipmap.check_on);
        }else if(type == 2){
            wxImg.setImageResource(R.mipmap.check_on);
            zfbImg.setImageResource(R.mipmap.check_off);
        }
    }

    private void pay(final int payType){
        RequestParams params = new RequestParams();
        List<Map<String,Object>> datas = new ArrayList<>();
        Map<String,Object> dataItem = null;
        for(Cart cart:mCartList){
            dataItem = new HashMap<>();
            dataItem.put("dataid",cart.getProductId());
            dataItem.put("dishnum",cart.getSaleCount());
            datas.add(dataItem);
        }
        Gson gson = new Gson();
        params.add("type",payType+"");
        params.add("money",priceSum+"");
        System.out.println(gson.toJson(datas));
        params.add("dishesDetailJson",gson.toJson(datas));
        String url = "";
        url = Common.URL+Common.DISHESORDER;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(map.get("data") == null || "".equals(map.get("data")+"")){
                    Toast.makeText(context,"支付失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }else{
                    DialogUIUtils.dismiss(dialog);
                    if(payType == 1){
                        payV2(map.get("data")+"");
                    }else if(payType == 2){
                        wxPay((Map<String, Object>)map.get("data"));
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    /**
     * 发起支付宝支付
     * @param orderInfo
     */
    public void payV2(final String orderInfo) {
        if (StringUtil.isNull(orderInfo)){
            Toast.makeText(context, "获取订单数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
//                        DialogUIUtils.dismiss(dialog);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 微信支付
     * @param orderInfo
     */
    private void wxPay(Map<String, Object> orderInfo){
        PayReq req = new PayReq();
//        req.appId			= orderInfo.get("appid")+"";
        req.appId			= Constants.APP_ID;
        req.partnerId		= orderInfo.get("partnerid")+"";
        req.prepayId		= orderInfo.get("prepayid")+"";
        req.nonceStr		= orderInfo.get("noncestr")+"";
        req.timeStamp		= StringUtil.stringToInt(orderInfo.get("timestamp")+"")+"";
        req.packageValue	= orderInfo.get("package")+"";
        req.sign			= orderInfo.get("sign")+"";
        // 将该app注册到微信
        api.registerApp(Constants.APP_ID);
//        IWXMsg.registerApp;
        api.sendReq(req);
    }


    ////////////////////////////////////popuwindow part
    private PopupWindow popupWindow;

    private void initPopWindow() {

        View contentView = LayoutInflater.from(context).inflate(R.layout.popu_cart, null);
        int height = Utils.getScreenHeight(context) - (cartFrame.getHeight()*2)+10;
        popupWindow = new PopupWindow(contentView, Utils.getScreenWidth(context),
                height);
        popupWindow.setContentView(contentView);

        //cart view init
        View clearView = contentView.findViewById(R.id.cart_clear_view);
        clearView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIHelper.clearCart(context, businessId);
                cartFrame.setEnabled(false);
                popupWindow.dismiss();
                rightAdapter.notifyDataSetChanged();
                leftAdapter.notifyDataSetChanged();
                priceSum = 0.0;
                buyNum = 0;
                showSeleted();
            }
        });
        popuListView = (ListView) contentView.findViewById(R.id.cart_list);
        getCart(popuListView);
        popupWindow.setFocusable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        View empView = contentView.findViewById(R.id.content_view);
        empView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
//        popupWindow.setOnDismissListener();

        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.ban_tou));
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.getBackground().setAlpha(0);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAsDropDown(cartFrame);
    }

    private CartAdapter cartAdapter = null;

    private void getCart(ListView listView) {
        mCartList = UIHelper.getCartList(context, businessId);
        cartAdapter = new CartAdapter(context, mCartList);
        listView.setAdapter(cartAdapter);
    }

    private void updateCart(Product mProduct) {
        //TODO 这里需要进行判断购物车是否存在 如果存在   则显示动画，否则第一次不显示动画
        int productId = mProduct.getProductId();
        String name = mProduct.getFoodName();
        double price = mProduct.getFoodPrice();
        Cart cart = new Cart();
        cart.setName(name);
        cart.setProductId(productId);
        cart.setSaleCount(count);
        cart.setPrice(price);
        UIHelper.getQueryIdCart(context, cart, productId,businessId);
    }

    private void deleteProductId(int productId) {
        UIHelper.deleteCart(context, productId);
    }

    /////////////////////////////////////product adapter////////////////////////////////////////////////

    class RightAdapter extends BaseAdapter implements SectionIndexer {
        private List<Product> list = null;
        private Context mContext;

        public RightAdapter(Context mContext, List<Product> list) {
            this.mContext = mContext;
            this.list = list;
        }


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return this.list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final ViewProductHolder viewProductHolder;
            final Product mProduct = list.get(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.product_item_new, null);
                TextView tvTag = (TextView) convertView.findViewById(R.id.cate_name);
                TextView tvSalecount = (TextView) convertView.findViewById(R.id.product_salecount_view);
                TextView tvTitle = (TextView) convertView.findViewById(R.id.product_name_view);
                ImageView productImage = (ImageView) convertView.findViewById(R.id.product_imageView);
                TextView countView = (TextView) convertView.findViewById(R.id.add_count_view);
                TextView tvPrice = (TextView) convertView.findViewById(R.id.product_price_view);
                ImageView removeProductImage = (ImageView) convertView.findViewById(R.id.delete_product_view);
                ImageView addProductImage = (ImageView) convertView.findViewById(R.id.add_product_view);
                viewProductHolder = new ViewProductHolder(tvTag, tvSalecount, tvTitle, productImage, countView, tvPrice, removeProductImage, addProductImage);

                convertView.setTag(viewProductHolder);
            } else {
                viewProductHolder = (ViewProductHolder) convertView.getTag();
            }
            //如果有该类型，则隐藏
            int section = getSectionForPosition(position);
            if (position == getPositionForSection(section)) {
                viewProductHolder.tvTag.setVisibility(View.VISIBLE);
                viewProductHolder.tvTag.setText(mProduct.getType());
            } else {
                viewProductHolder.tvTag.setVisibility(View.GONE);
            }
            viewProductHolder.tvTitle.setText(mProduct.getFoodName());
            viewProductHolder.tvPrice.setText("￥" + mProduct.getFoodPrice());
            viewProductHolder.tvSalecount.setText("已售" + mProduct.getSalesCount() + "份");

            int salecount = UIHelper.saleCount(context, mProduct.getProductId(), businessId);
            if (salecount > 0) {
                viewProductHolder.countView.setText(salecount + "");
                viewProductHolder.countView.setVisibility(View.VISIBLE);
                viewProductHolder.removeProductImage.setVisibility(View.VISIBLE);
            } else {
                viewProductHolder.countView.setText(0 + "");
                viewProductHolder.countView.setVisibility(View.GONE);
                viewProductHolder.removeProductImage.setVisibility(View.GONE);
            }


            //此处可以设置商品的图片========请在使用的过程中自行替换
            String url = mProduct.getImageUrl();
//            viewProductHolder.productImage.setImageResource(R.mipmap.default_icon);
            ImageLoader.getInstance().displayImage(Common.URL + url+"", viewProductHolder.productImage, ImageLoaderHelper.getOptionsDf());



            viewProductHolder.removeProductImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt(viewProductHolder.countView.getText().toString());
                    count--;
                    priceSum = priceSum - mProduct.getFoodPrice();
                    if (count < 1) {
                        viewProductHolder.removeProductImage.setVisibility(View.GONE);
                        viewProductHolder.countView.setVisibility(View.GONE);
                    }
                    viewProductHolder.countView.setText(count + "");
                    mProduct.setCount(count);
                    if (count == 0) {
                        deleteProductId(mProduct.getProductId());
                    } else {
                        updateCart(mProduct);
                    }
                    removeCart();
                    leftAdapter.notifyDataSetChanged();
                    //cartTotal(priceSum);
                }
            });

            viewProductHolder.addProductImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt(viewProductHolder.countView.getText().toString());
                    count++;
                    priceSum = priceSum + mProduct.getFoodPrice();
                    viewProductHolder.countView.setVisibility(View.VISIBLE);
                    viewProductHolder.removeProductImage.setVisibility(View.VISIBLE);
                    viewProductHolder.countView.setText(count + "");
                    mProduct.setCount(count);
                    int[] startLocation = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
                    v.getLocationInWindow(startLocation);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
                    ImageView ball = new ImageView(mContext);// buyImg是动画的图片，我的是一个小球
                    ball.setImageResource(R.mipmap.icon_fansnum_like_on);// 设置buyImg的图片
                    updateCart(mProduct);
                    setAnim(ball, startLocation);
                    leftAdapter.notifyDataSetChanged();
                    //cartTotal(priceSum);
                }
            });
            return convertView;
        }


        private class ViewProductHolder {
            TextView tvTag, tvSalecount, tvTitle;//,tvPrice,countView
            ImageView productImage;//,removeProductImage,addProductImage
            private final TextView countView;
            private final TextView tvPrice;
            private final ImageView removeProductImage;
            private final ImageView addProductImage;

            private ViewProductHolder(TextView tvTag, TextView tvSalecount, TextView tvTitle, ImageView productImage, TextView countView, TextView tvPrice, ImageView removeProductImage, ImageView addProductImage) {
                this.tvTag = tvTag;
                this.tvSalecount = tvSalecount;
                this.tvTitle = tvTitle;
                this.productImage = productImage;
                this.countView = countView;
                this.tvPrice = tvPrice;
                this.removeProductImage = removeProductImage;
                this.addProductImage = addProductImage;
            }
        }

        @Override
        public int getSectionForPosition(int position) {
            return list.get(position).getSeleteId();
        }

        /**
         * 查询api可以得知
         * 根据分类列的索引号获得该序列的首个位置
         * @param sectionIndex
         * @return
         */
        @Override
        public int getPositionForSection(int sectionIndex) {
            for (int i = 0; i < getCount(); i++) {
                int section = list.get(i).getSeleteId();
                if (section == sectionIndex) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public Object[] getSections() {
            // TODO 自动生成的方法存根
            return null;
        }

    }

    /////////////////////////////////////cart adapter////////////////////////////////////////////////

    class CartAdapter extends BaseAdapter {
        private List<Cart> list = null;
        private Context mContext;

        public CartAdapter(Context mContext, List<Cart> list) {
            this.mContext = mContext;
            this.list = list;
        }


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return this.list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final ViewHolder viewHolder;
            final Cart mCart = list.get(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.cart_item, null);
                TextView tvname = (TextView) convertView.findViewById(R.id.product_name_view);
                TextView countView = (TextView) convertView.findViewById(R.id.add_count_view);
                TextView totalPrice = (TextView) convertView.findViewById(R.id.product_totle_price_view);
                ImageView removeProductImage = (ImageView) convertView.findViewById(R.id.remove_product_view);
                ImageView addProductImage = (ImageView) convertView.findViewById(R.id.add_product_view);
                viewHolder = new ViewHolder(tvname, countView, totalPrice, removeProductImage, addProductImage);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.tvname.setText(mCart.getName());
            viewHolder.totalPrice.setText("￥" + mCart.getPrice());
            viewHolder.countView.setText(String.valueOf(mCart.getSaleCount()));
            if (Integer.parseInt(viewHolder.countView.getText().toString()) < 1) {
                viewHolder.removeProductImage.setVisibility(View.GONE);
                viewHolder.countView.setVisibility(View.GONE);
            } else {
                viewHolder.removeProductImage.setVisibility(View.VISIBLE);
                viewHolder.countView.setVisibility(View.VISIBLE);
            }
            viewHolder.removeProductImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt(viewHolder.countView.getText().toString());
                    count--;
                    priceSum = priceSum - mCart.getPrice();
                    if (count < 1) {
                        viewHolder.removeProductImage.setVisibility(View.GONE);
                        viewHolder.countView.setVisibility(View.GONE);
                    }
                    viewHolder.countView.setText(count + "");


                    removeCart();
                    //cartTotal(priceSum);

                    if (count < 1) {
                        deleteProductId(mCart.getProductId());
                        deleteData();
                    } else {
                        mCartList.get(position).setSaleCount(count);
                        updateCart(mCart);
                        rightAdapter.notifyDataSetChanged();
                    }
                    leftAdapter.notifyDataSetChanged();

                }
            });

            viewHolder.addProductImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt(viewHolder.countView.getText().toString());
                    count++;
                    priceSum = priceSum + mCart.getPrice();
                    viewHolder.countView.setVisibility(View.VISIBLE);
                    viewHolder.removeProductImage.setVisibility(View.VISIBLE);
                    viewHolder.countView.setText(count + "");
                    //TODO 这里需要进行判断购物车是否存在 如果存在   则显示动画，否则第一次不显示动画
                    updateCart(mCart);
                    addCart();
                    //cartTotal(priceSum);
                    mCartList.get(position).setSaleCount(count);
                    rightAdapter.notifyDataSetChanged();
                    leftAdapter.notifyDataSetChanged();
                }
            });


            return convertView;
        }

        private void deleteData() {
            try {
                mCartList = UIHelper.getCartList(context, businessId);
                popuListView.setAdapter(new CartAdapter(context, mCartList));
                rightAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        private void updateCart(Cart mCart) {
            int productId = mCart.getProductId();
            String name = mCart.getName();
            double price = mCart.getPrice();
            Cart cart = new Cart();
            cart.setProductId(productId);
            cart.setName(name);
            cart.setSaleCount(count);
            cart.setPrice(price);
            cart.setBusinessId(businessId);
            UIHelper.getQueryIdCart(context, cart, productId,businessId);
        }


        private class ViewHolder {
            TextView tvname;
            private final TextView countView;
            private final ImageView removeProductImage;
            private final ImageView addProductImage;
            private final TextView totalPrice;

            private ViewHolder(TextView tvname, TextView countView, TextView totalPrice, ImageView removeProductImage, ImageView addProductImage) {
                this.tvname = tvname;
                this.countView = countView;
                this.totalPrice = totalPrice;
                this.removeProductImage = removeProductImage;
                this.addProductImage = addProductImage;
            }
        }

    }


    static double convert(double value) {
        long l1 = Math.round(value * 100); //四舍五入
        double ret = l1 / 100.0; //注意：使用 100.0 而不是 100
        return ret;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UIHelper.clearCart(context, businessId);
    }
}
